package models

import (
	"registration-booking/global"
	"strconv"
)

type CardUser struct {
	ID
	CardId  uint `bson:"card_id" json:"card_id" gorm:"not null;comment:就诊卡id"`
	UserId  uint `bson:"user_id" json:"user_id" gorm:"not null;comment:用户id"`
	Default bool `json:"default" gorm:"not null;comment:是否默认"`
	Timestamps
	SoftDeletes
}

func (cardUser CardUser) GetUid() string {
	return strconv.Itoa(int(cardUser.ID.ID))
}

func (cardUser CardUser) Create() (err error) {
	err = global.App.DB.Create(&cardUser).Error
	return
}
func CancelOtherCardDefaults(uid, cardId uint) error {
	err := global.App.DB.Model(&CardUser{}).Where("user_id = ? AND card_id != ?", uid, cardId).Update("default", false).Error
	if err != nil {
		return err
	}

	return global.App.DB.Model(&CardUser{}).Where("user_id = ? AND card_id = ?", uid, cardId).Update("default", true).Error
}

func CancelCardDefault(uid, cardId uint) error {
	return global.App.DB.Model(&CardUser{}).Where("user_id = ? AND id = ?", uid, cardId).Update("default", false).Error
}
func FindCardUserById(id uint) (cardUser CardUser, err error) {
	err = global.App.DB.Where("id = ?", id).Find(&cardUser).Error
	return
}

func FindCardUserByCardId(cardId uint) (cardUser []CardUser, err error) {
	err = global.App.DB.Where("card_id = ?", cardId).Find(&cardUser).Error
	return
}

func FindCardUserByUserId(uid uint) (cardUsers []CardUser, err error) {
	err = global.App.DB.Where("user_id = ?", uid).Order("`card_users`.`default` DESC").Find(&cardUsers).Error
	return
}

func FindCardUserByUserIdAndCardId(uid, cid uint) (cardUsers []CardUser, err error) {
	err = global.App.DB.Where("user_id = ? AND card_id = ?", uid, cid).Find(&cardUsers).Error
	return
}

func DeleteCardUserByCardId(cardId uint) (err error) {
	err = global.App.DB.Where("card_id = ?", cardId).Delete(&CardUser{}).Error
	return
}
